CREATE OR REPLACE FUNCTION getAnyNotNull(ANYELEMENT, ANYELEMENT) RETURNS ANYELEMENT AS
$$
  SELECT CASE WHEN $1 = NULL THEN $2 ELSE $1 END;
$$ LANGUAGE SQL STRICT;

DROP AGGREGATE IF EXISTS ANYVALUE (anyelement) CASCADE;
CREATE AGGREGATE ANYVALUE (anyelement) (
  sfunc = getAnyNotNull,
  stype = anyelement
);

